package com.aspire.aimini.model.query;

import com.aspire.aimini.constant.CommonConstant;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.Data;


import java.io.Serializable;

/**
 * 基础查询对象
 *
 * @author wangguiyou
 * @date 2024-12-19
 * @description 包含分页参数的基础查询对象
 */
@Data
@Schema(description = "基础查询对象")
public class BaseQuery implements Serializable {

    private static final long serialVersionUID = 1L;

    @Schema(description = "页码", example = "1")
    @Min(value = 1, message = "页码不能小于1")
    private Integer pageNum = CommonConstant.DEFAULT_PAGE_NUM;

    @Schema(description = "页面大小", example = "10")
    @Min(value = 1, message = "页面大小不能小于1")
    @Max(value = 100, message = "页面大小不能超过100")
    private Integer pageSize = CommonConstant.DEFAULT_PAGE_SIZE;

    @Schema(description = "排序字段", example = "createTime")
    private String orderBy;

    @Schema(description = "排序方式：asc-升序，desc-降序", example = "desc")
    private String orderDirection = "desc";

    /**
     * 获取排序SQL
     *
     * @return 排序SQL
     */
    public String getOrderSql() {
        if (orderBy == null || orderBy.trim().isEmpty()) {
            return "create_time desc";
        }

        // 转换驼峰命名为下划线命名
        String column = camelToUnderscore(orderBy);
        String direction = "desc".equalsIgnoreCase(orderDirection) ? "desc" : "asc";

        return column + " " + direction;
    }

    /**
     * 驼峰命名转下划线命名
     *
     * @param camelCase 驼峰命名字符串
     * @return 下划线命名字符串
     */
    private String camelToUnderscore(String camelCase) {
        if (camelCase == null || camelCase.isEmpty()) {
            return camelCase;
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < camelCase.length(); i++) {
            char c = camelCase.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    result.append('_');
                }
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }

        return result.toString();
    }
}